var redisDb = {};
var redis = require("redis");
var client = redis.createClient('6379', '192.168.30.191', {"password": 'JSMK5THxv9u'});

client.on('error',function (err) {
    console.log('redis error：'+err);
});

client.on('connect',function () {
    console.info('redis连接成功...')
});

/**
 *
 * @param dbNum 库号
 * @param key 键
 * @param value 值
 * @param expire 过期时间（单位：秒，可为空，为空则不过期）
 * @param callback 回调
 */
redisDb.initSet = function (dbNum,key,value,expire,callback) {
    console.log('~~~~~~~~~~')
    client.select(dbNum,function (err) {
        if (err){
            console.log('~~~~~~redis set 选库失败：'+err);
        }else {
            client.set(key,value,function (err,result) {
                if (err){
                    console.log('~~~~~~redis插入失败：'+err);
                    callback(err,null);
                    return
                }
                if (!isNaN(expire) && expire>0){
                    client.expire(key, parseInt(expire));
                }
                callback(err, result);
            })
        }
    })
};

redisDb.set = function(callback){
    redisDb.initSet(1, 'db', JSON.stringify(global.db), 86400, callback)
}

redisDb.initGet = function (dbNum,key,callback) {
    client.select(dbNum,function (err) {
        if (err){
            console.log('redis get 选库失败：'+err);
        }else {
            client.get(key,function (err,result) {
                if (err){
                    console.log('redis获取失败：'+err);
                    callback(err,null);
                    return
                }
                global.db = JSON.parse(result)
                callback(err, JSON.parse(result));
            })
        }
    })
};
redisDb.get = function(callback){
    redisDb.initGet(1, 'db', callback)
}

module.exports = redisDb;
